<%@ page import="com.dsj.cart.CartGoods" %>
<%@ page import="java.util.Vector" %><%--
  添加商品到购物车
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    //获取request中的请求参数：商品编号及商品价格
    int goodsId = Integer.parseInt(request.getParameter("goodsId"));
    float goodsPrice = Float.parseFloat(request.getParameter("price"));
    //购买的商品数量
    int buyGoodsNumber = 1;

    //设置标志，用于判断本次添加的商品是否不在原有的购物车中
    boolean flag = true;

    //构造商品对象，默认每次选一个商品
    CartGoods cartGoods = new CartGoods(goodsId, goodsPrice, buyGoodsNumber);
    //判断用户是否已经有购物车
    Vector cart = (Vector) session.getAttribute("__CART__");
    if (cart == null) {
        //如果没有购物车，则创建一个空的购物车
        cart = new Vector();
    }else {
        for (int i = 0; i < cart.size(); i++) {
            CartGoods boughtGoods = (CartGoods) cart.elementAt(i);
            //如果购物车中已经有该商品，则数量加1
            if (boughtGoods.id == cartGoods.id) {
                boughtGoods.number++;
                cart.setElementAt(boughtGoods, i);
                flag = false;
            }

        }
    }
    //原购物车中没有要添加的商品
    if(flag) {
        cart.addElement(cartGoods);
    }
    //将购物车存放到session中
    session.setAttribute("__CART__", cart);

    out.println("<script>alert('添加成功！');window.close();</script>");
%>
